package org.sfx.rich

import org.sfx.util.Capabilities._
import javafx.beans.value.ObservableValue
import javafx.beans.value.ChangeListener
import javafx.beans.value.WeakChangeListener

class RichCanAddRemoveChangeListener[T](underlying: CanAddRemoveChangeListener[T]) {
  def addChangeListener[U >: T](f: (ObservableValue[_ <: U], U, U) => Unit): ChangeListener[U] = {
    val listener = new ChangeListener[U] {
      def changed(observableValue: ObservableValue[_ <: U], oldValue: U, newValue: U): Unit = {
        f(observableValue, oldValue, newValue)
      }
      def detach() = underlying.removeListener(this)
    }
    underlying.addListener(listener)
    listener
  }
  
  def addFirstChangeListener[U >: T](f: (ObservableValue[_ <: U], U, U) => Unit): Unit = {
    val listener = new ChangeListener[U] {
      def changed(observableValue: ObservableValue[_ <: U], oldValue: U, newValue: U): Unit = {
        underlying.removeListener(this)
        f(observableValue, oldValue, newValue)
      }
    }
    underlying.addListener(listener)
  }
}
